package Web;

import com.alibaba.fastjson.JSON;
import org.apache.ibatis.session.SqlSession;
import org.example.Mapper.MessageMapper;
import org.example.Mapper.UserMapper;
import org.example.MybatisUtils;
import org.example.PoJo.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/GetUserInformation")
public class GetUserInformation  extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        System.out.println("aaaa");
//
        Map<String,Object> map=new HashMap<>();
        User user = mapper.GetUser(req.getParameter("username"),req.getParameter("password"));
        if (user!=null){
            req.getSession().setAttribute("self",user);
            map.put("checklogin",true);
            MessageMapper messageMapper=sqlSession.getMapper(MessageMapper.class);
            req.getSession().setAttribute("Messages",messageMapper.GetMessageList());
            map.put("Messages",messageMapper.GetMessageList());
        }else {
            map.put("checklogin",false);
        }
        //查询不用提交事务
//        System.out.println("user: "+user);
        sqlSession.close();
        String json = JSON.toJSONString(map);
        PrintWriter pw = resp.getWriter();
        pw.print(json);
    }
}
